<template>
  <div>
    <el-drawer
      :title="skuShortName"
      :visible="visible"
      size="90vw"
      @close="closeDialog"
      append-to-body
    >
      <div style="margin: 20px 40px">
        <el-form
          :model="dataForm"
          :rules="dataRule"
          ref="dataForm"
          label-width="100px">
          <el-collapse v-model="activeNames">
            <el-collapse-item name="1">
              <template slot="title">
                <div>
                  <i class="header-icon el-icon-goods"></i>
                  <span class="title-size">基本信息</span>
                </div>
              </template>
              <div v-for="(sku, index) in dataForm.skus" :key="index" style="padding:20px 0px" class="border-buttom">
                <el-row>
                  <el-form-item label="商品sku全称" :prop="'skus.' + index + '.skuName'"
                    :rules="[{ required: true, message:'商品sku全称不能为空', trigger: 'blur'}]">
                    <el-input
                      v-model="sku.skuName"
                      placeholder="请输入商品sku全称"
                    ></el-input>
                  </el-form-item>
                </el-row>
                <el-row>
                  <el-form-item label="商品sku简称" :prop="'skus.' + index + '.skuShortName'"
                    :rules="[{ required: true, message:'商品sku简称不能为空', trigger: 'blur'}]">
                    <el-input
                      v-model="sku.skuShortName"
                      placeholder="请输入商品sku简称"
                      maxlength="6"
                    ></el-input>
                  </el-form-item>
                </el-row>

                <el-row>
                  <el-form-item label="罐装数量" :prop="'skus.' + index + '.canningCount'"
                    :rules="[{ required: true, validator:validatorNumber, message:'罐装数量不能为空', trigger: 'blur'}]">
                    <el-input
                      v-model.number="sku.canningCount"
                      placeholder="请输入罐装数量"
                    ></el-input>
                  </el-form-item>
                </el-row>

                <el-row>
                  <el-form-item label="袋装数量" :prop="'skus.' + index + '.bagCount'"
                    :rules="[{ required: true, validator:validatorNumber, message:'袋装数量不能为空', trigger: 'blur'}]">
                    <el-input
                      v-model.number="sku.bagCount"
                      placeholder="请输入袋装数量"
                    ></el-input>
                  </el-form-item>
                </el-row>

                <el-row>
                  <el-form-item label="条装数量" :prop="'skus.' + index + '.stripCount'"
                    :rules="[{ required: true, validator:validatorNumber, message:'条装数量不能为空', trigger: 'blur'}]">
                    <el-input
                      v-model.number="sku.stripCount"
                      placeholder="请输入条装数量"
                    ></el-input>
                  </el-form-item>
                </el-row>

                <el-row>
                  <el-form-item label="积分策略" :prop="'skus.' + index + '.pointPolicyId'">
                    <el-select
                      v-model="sku.pointPolicyId"
                      filterable
                      placeholder="请选择积分策略"
                      clearable
                      style="width:100%"
                    >
                      <el-option
                        v-for="dict in pointPolicyList"
                        :key="dict.id"
                        :label="dict.policyName"
                        :value="dict.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-row>

                <el-row>
                  <el-form-item label="sku轮播图" :prop="'skus.' + index + '.bannerImages'" 
                    :rules="[{ required: true, message:'sku轮播图不能为空', trigger: 'blur'}]">
                    <ImagesUpload v-model="sku.bannerImages"></ImagesUpload>
                    <span style="color:#FF0000">轮播图第一张为商品主图</span>
                  </el-form-item>
                </el-row>
                <el-row>
                  <el-form-item label="sku详情图" :prop="'skus.' + index + '.detailImages'" 
                    :rules="[{ required: true, message:'sku详情图不能为空', trigger: 'blur'}]">
                    <ImagesUpload v-model="sku.detailImages"></ImagesUpload>
                  </el-form-item>
                </el-row>

                <el-table :data="[sku]" border style="width: 100%">
                  <el-table-column align="center" v-for="(spuSpec, index1) in goodsSpuSpecList" :key="index1" :label="spuSpec.value">
                    <template slot-scope="{row}">
                      <div v-for="(spec,index3) in row.specs" :key="index3">
                        <span v-if="spuSpec.specId == spec.specId">{{spec.specValueName}}</span>
                      </div>
                    </template>
                  </el-table-column>
                  
                  <el-table-column
                    align="center">
                    <template slot="header">
                      <span class="required-table-column">*</span>
                      <span>销售价格</span>
                    </template>  
                    <template slot-scope="{row}">
                      <el-form-item label="" :prop="'skus.' + index + '.sellPrice'" label-width="0"
                        :rules="[{ required: true, validator:validatorMoney, trigger: 'blur'}]" style="margin-top:18px">
                        <el-input v-model.number="row.sellPrice" placeholder="请输入销售价格" ></el-input>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center">
                    <template slot="header">
                      <span class="required-table-column">*</span>
                      <span>市场价格</span>
                    </template>  
                    <template slot-scope="{row}">
                      <el-form-item label="" :prop="'skus.' + index + '.marketPrice'" label-width="0" 
                        :rules="[{ required: true, validator:validatorMoney, trigger: 'blur'}]" style="margin-top:18px">
                        <el-input v-model.number="row.marketPrice" placeholder="请输入市场价格" ></el-input>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center">
                    <template slot="header">
                      <span class="required-table-column">*</span>
                      <span>虚拟销量</span>
                    </template> 
                    <template slot-scope="{row}">
                      <el-form-item label="" :prop="'skus.' + index + '.virtualSales'" label-width="0" 
                        :rules="[{ required: true, validator:validatorNumber, trigger: 'blur'}]" style="margin-top:18px">
                        <el-input v-model.number="row.virtualSales" placeholder="请输入虚拟销量" ></el-input>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <!-- <el-table-column
                    align="center">
                    <template slot="header">
                      <span class="required-table-column">*</span>
                      <span>获取积分</span>
                    </template> 
                    <template slot-scope="{row}">
                      <el-form-item label="" :prop="'skus.' + index + '.point'" label-width="0" 
                        :rules="[{ required: true, validator:validatorNumber, trigger: 'blur'}]" style="margin-top:18px">
                        <el-input v-model.number="row.point" placeholder="请输入获取积分" ></el-input>
                      </el-form-item>
                    </template>
                  </el-table-column> -->
                  <!-- <el-table-column
                    align="center">
                    <template slot="header">
                      <span class="required-table-column">*</span>
                      <span>一级分润</span>
                    </template> 
                    <template slot-scope="{row}">
                      <el-form-item label="" :prop="'skus.' + index + '.firstProfit'" label-width="0"
                        :rules="[{ required: true, validator:validatorMoney, trigger: 'blur'}]" style="margin-top:18px">
                        <el-input v-model.number="row.firstProfit" placeholder="请输入一级分润" ></el-input>
                      </el-form-item>
                    </template>
                  </el-table-column> -->
                  <!-- <el-table-column
                    align="center">
                    <template slot="header">
                      <span class="required-table-column">*</span>
                      <span>二级分润</span>
                    </template> 
                    <template slot-scope="{row}">
                      <el-form-item label="" :prop="'skus.' + index + '.secondProfit'" label-width="0"
                        :rules="[{ required: true, validator:validatorMoney, trigger: 'blur'}]" style="margin-top:18px">
                        <el-input v-model.number="row.secondProfit" placeholder="请输入二级分润" ></el-input>
                      </el-form-item>
                    </template>
                  </el-table-column> -->
                  <el-table-column
                    label="首页一级推荐"
                    align="center">
                    <template slot-scope="{row}">
                      <el-form-item label="" :prop="'skus.' + index + '.hasMain'" label-width="0" style="margin-top:18px">
                        <el-switch v-model="row.hasMain" active-value="1" inactive-value="0"></el-switch>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="首页二级推荐"
                    align="center">
                    <template slot-scope="{row}">
                      <el-form-item label="" :prop="'skus.' + index + '.hasSubMain'" label-width="0" style="margin-top:18px">
                        <el-switch v-model="row.hasSubMain" active-value="1" inactive-value="0"></el-switch>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="推荐列表"
                    align="center">
                    <template slot-scope="{row}">
                      <el-form-item label="" :prop="'skus.' + index + '.hasRecommend'" label-width="0" style="margin-top:18px">
                        <el-switch v-model="row.hasRecommend" active-value="1" inactive-value="0"></el-switch>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="上架状态"
                    align="center">
                    <template slot-scope="{row}">
                      <el-form-item label="" :prop="'skus.' + index + '.status'" label-width="0" style="margin-top:18px">
                        <el-switch v-model="row.status" active-value="1" inactive-value="0"></el-switch>
                      </el-form-item>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-collapse-item>
            <el-collapse-item name="2">
              <template slot="title">
                <div>
                  <i class="header-icon el-icon-s-order"></i>
                  <span class="title-size">礼品信息</span>
                </div>
              </template>

              <div style="margin:20px 0px" v-if="dataForm.skus.length > 0">
                <el-row type="flex" justify="center">
                  <el-button
                    icon="el-icon-plus"
                    type="primary"
                    @click="handleAddSkuGift(dataForm.skus[0])"
                    >添加赠品</el-button>
                </el-row>

                <el-table :data="dataForm.skus[0].gifts" border style="width: 100%; margin-top:10px" v-if="dataForm.skus[0].gifts.length > 0">
                  <el-table-column
                    align="center">
                    <template slot="header">
                      <span class="required-table-column">*</span>
                      <span>赠品展示图</span>
                    </template> 
                    <template slot-scope="scope">
                      <el-form-item label="" :prop="'skus.0.gifts.' + scope.$index +  '.coverImage'" label-width="20" 
                        :rules="[{ required: true, message: '赠品展示图必须选择，不能为空', trigger: 'blur'}]" style="margin-top:18px">
                        <ImageUploadSingle v-model="scope.row.coverImage"></ImageUploadSingle>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="赠品名称"
                    align="center"
                    prop="giftName">
                  </el-table-column>
                  <el-table-column
                    header-align="center"
                    align="center"
                    label="赠品图片">
                    <template slot-scope="scope">
                      <el-image
                        style="width: 67px; height: 67px"
                        :src="getGiftCover(scope.row.bannerImages)"
                        :preview-src-list="[getGiftCover(scope.row.bannerImages)]">
                      </el-image>
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center">
                    <template slot="header">
                      <span class="required-table-column">*</span>
                      <span>赠送数量（默认一个）</span>
                    </template> 
                    <template slot-scope="scope">
                      <el-form-item label="" :prop="'skus.0.gifts.' + scope.$index +  '.count'" label-width="0" 
                        :rules="[{ required: true, validator:validatorNumber, trigger: 'blur'}]" style="margin-top:18px">
                        <el-input v-model.number="scope.row.count" placeholder="请输入赠送数量" ></el-input>
                      </el-form-item>
                    </template>
                  </el-table-column>

                  <el-table-column header-align="center" align="center" label="操作">
                    <template slot-scope="scope">
                      <el-button
                        type="text"
                        size="small"
                        icon="el-icon-delete"
                        @click="handleDeleteGift(scope.row.id)"
                        >删除</el-button
                      >
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-collapse-item>
          </el-collapse>
        </el-form>
      </div>
      <div class="dialog__footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-drawer>

    <GiftsForm  
        v-if="giftsFormVisible"
        ref="giftsForm"
        :visible.sync="giftsFormVisible">
    </GiftsForm>
  </div>
</template>

<script>
  import {getSkuById, updateSkuById} from '@/api/shop/goods/spu';
  import ImagesUpload from "@/components/imagesUpload";
  import GiftsForm from './gifts.vue';
  import ImageUploadSingle from '@/components/imageUploadSingle';
  import {getPointPolicyList} from '@/api/platform/point_policy';

  export default {
    props:{
      visible: {
        type: Boolean,
        default: false
      },
    },
    data(){
      return{
        activeNames:['1', '2'],
        dataForm:{
          skus:[]
        },
        dataRule:{

        },
        skuShortName:'',
        // 商品和规格对应关系
        goodsSpuSpecList:[],
        // 积分策略列表
        pointPolicyList:[],
        giftsFormVisible:false
      }
    },
    components: {
      ImagesUpload,
      GiftsForm,
      ImageUploadSingle
    },
    methods:{

      /**
       * 初始化
       */
      init(spuId ,skuId, skuShortName){
        this.skuShortName = skuShortName
        // 获取积分策略
        this.getPointPolicyList()
        if(skuId){
          getSkuById({
            id: spuId,
            skuId, skuId
          }).then(response=>{
            // this.dataForm = response.data.data;
            // this.dataForm.bannerImages = this.dataForm.bannerImages.split(',')
            // this.dataForm.detailImages = this.dataForm.detailImages.split(',')
            // console.log(this.dataForm)
            this.dataForm = response.data.data;
            this.dataForm.spuSpec.forEach(item=>{
              item.leaf = JSON.parse(item.leaf)
              this.goodsSpuSpecList.push(item)
            })

            this.dataForm.skus.forEach(sku=>{
              sku.bannerImages = sku.bannerImages ? JSON.parse(sku.bannerImages) : []
              sku.detailImages = sku.detailImages ? JSON.parse(sku.detailImages) : []

              // 销售价格转元
              sku.sellPrice = this.formatMoneyToYuan(sku.sellPrice)
              // 市场价格转分
              sku.marketPrice = this.formatMoneyToYuan(sku.marketPrice)
              // 一级分润转分
              sku.firstProfit = this.formatMoneyToYuan(sku.firstProfit)
              // 二级分润转分
              sku.secondProfit = this.formatMoneyToYuan(sku.secondProfit)

              sku.gifts.forEach(gift=>{
                //gift.bannerImages = gift.bannerImages ? JSON.parse(gift.bannerImages) : []
                if(gift.coverImage){
                  let arr = JSON.parse(gift.coverImage)
                  if(arr.length > 0){
                    gift.coverImage = arr[0]
                  }
                }
              })
            })
            console.log(this.dataForm)
          })
        }
      },

      /**
       * 获取积分策略列表
       */
      getPointPolicyList(){
        getPointPolicyList().then(res=>{
          this.pointPolicyList = res.data.data
        })
      },

      /**
       * 提交
       */
      handleSubmit(){
        this.$refs["dataForm"].validate((valid) => {
          if (valid) {
            let submitData = JSON.parse(JSON.stringify(this.dataForm))
            submitData.skus.forEach(sku=>{
              sku.bannerImages = sku.bannerImages.map(p=>p.materialId).join()
              sku.detailImages = sku.detailImages.map(p=>p.materialId).join()

              // 销售价格转元
              sku.sellPrice = this.formatMoneyToFen(sku.sellPrice)
              // 市场价格转分
              sku.marketPrice = this.formatMoneyToFen(sku.marketPrice)
              // 一级分润转分
              //sku.firstProfit = this.formatMoneyToFen(sku.firstProfit)
              // 二级分润转分
              //sku.secondProfit = this.formatMoneyToFen(sku.secondProfit)

              sku.gifts.forEach(gift=>{
                delete gift.bannerImages
                gift.coverImage = gift.coverImage.materialId
              })
            })

            console.log(submitData)
            
            if(submitData.id){
              updateSkuById(submitData).then((data) => {
                this.$notify.success("修改成功");
                this.$emit("refreshDataList");
                this.closeDialog()
              }).catch(() => {
                this.canSubmit = true;
              });
            }
          }
        })
      },

      /**
       * 验证金额
       */
      validatorMoney (rule, value, callback)  {
        if(value === ''){
          let field = ''
          callback(new Error(`必填项不能为空`))
        } else {
          callback()
        }
      },

      /**
       * 验证数字
       */
      validatorNumber(rule, value, callback){
        if(value === ''){
          let field = ''
          callback(new Error(`必填项不能为空`))
        } else {
          callback()
        }
      },

      /**
       * 添加礼品
       */
      handleAddSkuGift(){
        this.giftsFormVisible = true
        this.$nextTick(() => {
          this.$refs.giftsForm.init(this.dataForm.skus[0]);
        });
      },

      /**
       * 获得主图
       */
      getGiftCover(item){
        if(item){
          let images = JSON.parse(item)
          if(images.length > 0){
            return images[0].materialUrl
          } else {
            return ''
          }
        } else {
          return ''
        }
        
        // if(item.bannerImages.length > 0){
        //   return item.bannerImages[0].materialUrl
        // } else {
        //   return ''
        // }
      },

      /**
       * 删除SKU的赠品
       */
      handleDeleteGift(giftId){
        for(let i = 0; i < this.dataForm.skus[0].gifts.length; i++){
          if(this.dataForm.skus[0].gifts[i].id == giftId){
            this.dataForm.skus[0].gifts.splice(i,1)
            break;
          }
        }
      },
      
      /**
       * 重置表单
       */
      closeDialog() {
        this.$emit('update:visible', false)
      },
    }
  }
</script>


<style scoped>

.header-icon{
  font-size: 16px;
  margin-right: 10px;
}

.title-size{
  font-size: 16px;
}

.dialog__footer {
  display: block;
  padding: 10px 16px;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  border-top: 1px solid #f0f0f0;
  width: 100%;
  position: absolute;
  left: 0;
  bottom: 0;
  background-color: #fff;
  text-align: right;
}

.border-buttom{
  border-bottom: #cccccc solid 1px;
}

.required-table-column{
  margin-right:2px; color:#FF0000
}

/* .el-form-item{
    margin-bottom: 0px;
} */
</style>
